package com.example.admin.utils;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class CodeToNameSerializer<T> extends JsonSerializer<T> implements ContextualSerializer {

    private static final Logger logger = LoggerFactory.getLogger(CodeToNameSerializer.class);

    private String codeType;

    private String nameField;

    public CodeToNameSerializer() {
        super();
    }

    public CodeToNameSerializer(String codeType, String nameField) {
        this.codeType = codeType;
        this.nameField = nameField;
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        logger.info("SERIALIZERPROVIDER: {}, BEANPROPERTY: {}", serializerProvider, beanProperty);
        CodeToName annotation = beanProperty.getAnnotation(CodeToName.class);
        if (annotation == null) {
            return new CodeToNameSerializer<>();
        }
        return new CodeToNameSerializer<>(annotation.codeClsType(), annotation.codeNameFiled());
    }

    @Override
    public void serialize(T o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        logger.info("O: {}, JSONGENERATOR: {}, SERIALIZERPROVIDER: {}", o, jsonGenerator, serializerProvider);
        jsonGenerator.writeObject(o);
//        String nameVal = CodeToNameUtil.getCodeNameByCode(s, codeType);
        jsonGenerator.writeStringField(jsonGenerator.getOutputContext().getCurrentName() + "Name", CodeToNameUtil.sex.get(o));
        logger.info("CODETYPE: {}, NAMEFIELD: {}", codeType, nameField);
    }
}

